package org.lc.stk.web.controller.course;

import java.util.List;

import org.lc.stk.model.course.Course;
import org.lc.stk.service.course.ChapterService;
import org.lc.stk.service.course.CourseService;
import org.lc.stk.service.course.KnowledgePointService;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.web.response.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 课程管理控制器
 * 提供课程相关的REST API，包括课程的CRUD操作和章节、知识点管理
 */
@RestController
@RequestMapping("/api/v1/courses")
@Tag(name = "课程管理", description = "课程相关的增删改查及章节知识点管理接口")
@Validated
public class CourseController {

    private final CourseService courseService;
    private final ChapterService chapterService;
    private final KnowledgePointService knowledgePointService;

    public CourseController(CourseService courseService, ChapterService chapterService, 
            KnowledgePointService knowledgePointService) {
        this.courseService = courseService;
        this.chapterService = chapterService;
        this.knowledgePointService = knowledgePointService;
    }

    @Operation(summary = "创建课程", description = "创建一个新的课程，并返回创建结果")
    @PostMapping
    @PreAuthorize("@resourcePermissionEvaluator.hasGlobalPermission(authentication, 'course', 'create')")
    public ResponseEntity<ApiResponse<Course>> createCourse(@RequestBody @Validated Course course) {
        if (courseService.existsByName(course.getName())) {
            throw new BusinessException("课程名称已存在");
        }
        Course savedCourse = courseService.save(course);
        return ResponseEntity.ok(ApiResponse.success(savedCourse, "课程创建成功"));
    }

    @Operation(summary = "更新课程", description = "根据课程ID更新课程信息")
    @PutMapping("/{courseId}")
    @PreAuthorize("@resourcePermissionEvaluator.hasPermission(authentication, 'course', #courseId.toString(), 'edit')")
    public ResponseEntity<ApiResponse<Course>> updateCourse(
            @PathVariable Integer courseId,
            @RequestBody @Validated Course course) {
        if (!courseService.existsById(courseId)) {
            throw new BusinessException("课程不存在");
        }
        course.setId(courseId);
        Course updatedCourse = courseService.update(course);
        return ResponseEntity.ok(ApiResponse.success(updatedCourse, "课程更新成功"));
    }

    @Operation(summary = "删除课程", description = "根据课程ID删除课程")
    @DeleteMapping("/{courseId}")
    @PreAuthorize("@resourcePermissionEvaluator.hasPermission(authentication, 'course', #courseId.toString(), 'delete')")
    public ResponseEntity<ApiResponse<?>> deleteCourse(@PathVariable Integer courseId) {
        if (!courseService.existsById(courseId)) {
            throw new BusinessException("课程不存在");
        }
        courseService.delete(courseId);
        return ResponseEntity.ok(ApiResponse.success("课程删除成功"));
    }

    @Operation(summary = "获取课程详情", description = "根据课程ID获取课程详情")
    @GetMapping("/{courseId}")
    @PreAuthorize("@resourcePermissionEvaluator.hasPermission(authentication, 'course', #courseId.toString(), 'view')")
    public ResponseEntity<ApiResponse<Course>> getCourse(@PathVariable Integer courseId) {
        Course course = courseService.findById(courseId);
        if (course == null) {
            throw new BusinessException("课程不存在");
        }
        return ResponseEntity.ok(ApiResponse.success(course, "获取课程成功"));
    }

    @Operation(summary = "获取课程列表", description = "获取所有课程的列表")
    @GetMapping
    @PreAuthorize("@resourcePermissionEvaluator.hasGlobalPermission(authentication, 'course', 'view')")
    public ResponseEntity<ApiResponse<List<Course>>> listCourses() {
        List<Course> courses = courseService.findAll();
        return ResponseEntity.ok(ApiResponse.success(courses, "获取课程列表成功"));
    }

    @Operation(summary = "管理章节", description = "管理指定课程的章节信息")
    @PutMapping("/{courseId}/chapters")
    @PreAuthorize("@resourcePermissionEvaluator.hasPermission(authentication, 'course', #courseId.toString(), 'manage_chapters')")
    public ResponseEntity<ApiResponse<?>> manageChapters(
            @PathVariable Integer courseId,
            @RequestBody @Validated List<Object> chaptersData) {
        if (!courseService.existsById(courseId)) {
            throw new BusinessException("课程不存在");
        }
        // TODO: 实现章节管理逻辑
        // 1. 验证章节数据结构
        // 2. 更新章节信息
        // 3. 维护章节之间的关系
        return ResponseEntity.ok(ApiResponse.success("章节管理成功"));
    }

    @Operation(summary = "管理知识点", description = "管理指定课程的知识点信息")
    @PutMapping("/{courseId}/knowledge-points")
    @PreAuthorize("@resourcePermissionEvaluator.hasPermission(authentication, 'course', #courseId.toString(), 'manage_knowledge_points')")
    public ResponseEntity<ApiResponse<?>> manageKnowledgePoints(
            @PathVariable Integer courseId,
            @RequestBody @Validated List<Object> knowledgePointsData) {
        if (!courseService.existsById(courseId)) {
            throw new BusinessException("课程不存在");
        }
        // TODO: 实现知识点管理逻辑
        // 1. 验证知识点数据结构
        // 2. 更新知识点信息
        // 3. 维护知识点之间的关系
        return ResponseEntity.ok(ApiResponse.success("知识点管理成功"));
    }
}